package com.liu.webstore.interceptor;

import com.liu.webstore.entity.User;
import com.liu.webstore.service.DataService;
import com.liu.webstore.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @Author LiuYumei
 * @Date 2022/8/28 22:13
 */
@Component
public class DataInterceptor implements HandlerInterceptor {
    @Autowired
    private DataService dataService;
    @Autowired
    private HostHolder hostHolder;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 统计UV
        String userIp = request.getRemoteHost();
        dataService.recordUV(userIp);
        // 统计DAU
        User user = hostHolder.getUser();
        if (Objects.nonNull(user)) {
            dataService.recordDAU(user.getId());
        }
        return true;
    }
}
